import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  // 素材系统跳转 拼接token
  if( to.path === '/dashboard/index' && Object.keys(to.query).length !== 0 ){
    storage.set( ACCESS_TOKEN, to.query.token )
    store.commit('SET_TOKEN',to.query.token)
    store.commit('SET_INFO',to.query.info)
    store.commit('SET_SYSYTEMALIASES','ADV_OCEAN')
  }

  NProgress.start() // start progress bar

  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`))

  /* has token */
  if (storage.get(ACCESS_TOKEN)) { // 获取Token
    store.dispatch('SystemAliases', 'ADV_OCEAN')
    if (to.path === '/user/login' ) {
      next({ path: '/dashboard/index' })
      NProgress.done()
    } else {
      next()
      // check login user.roles is null
      if (store.getters.info) {
        // request login userInfo
        store.dispatch('GetInfo').then(res => {
          next()
        }).catch(() => {
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path:'/user/login' })
      // next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
